<?php
if (!(defined('IN_IA')))
{
    exit('Access Denied');
}
/**
 * User: 邓志锋 <280160522@qq.com> <http://www.diygw.com>
 * Date: 2018-07-28
 * Time: 下午 6:06
 */
class Dashboard_Diygwcom extends DiygwcomAction
{
    public function sign($package){
        global $_GPC, $_W;
        $config = pdo_get(getTableName('CONFIG'), array('name' => 'auth','uniacid'=>$_W['uniacid']), array('name', 'value'));
        if(!$config){
            header('location:' . $this->createWebUrl('dashboard_auth', array('m'=>'diygwcom_app')));
            exit();
            //message('授权失败', $this->createMobileUrl('dashboard_set'), 'error');
        }
        $config=json_decode($config['value'],true);

        $package['appid'] = $config['appid'];
        $package['nonce_str'] = random(32);
        $package['time_start'] = date('YmdHis', TIMESTAMP);
        $package['time_expire'] = date('YmdHis', TIMESTAMP + 3600);
        ksort($package, SORT_STRING);
        $string1 = '';
        foreach ($package as $key => $v )
        {
            if (empty($v)){
                continue;
            }
            $string1 .= $key . '=' . $v . '&';
        }
        $string1 .= 'appsecret=' . $config['appsecret'];
        $package['sign'] = strtoupper(md5($string1));
        return $package;
    }

    public function index()
    {
        global $_GPC, $_W;

        $psize 	= 10;
        $index 	= max(1, intval($_GPC['page']));


        $package = $this->sign([]);

        $response = ihttp_post('http://www.diygw.com/auth/update.html', $package);

        if(isset($response['content'])&& !empty($response['content'])){
            $remotes=json_decode($response['content'],true)['content'];
        }

        $datas 	= pdo_getslice(getTableName('DASHBOARD'), array(), array($index, $psize), $total, array(), '', array('id desc'));

        $data=[];
        if(isset($remotes)&&!empty($remotes)){
            $remotedata=[];
            $existdata=[];

            foreach ($remotes  as $rkey => $ritem){
                $flag = true;
                foreach ($datas  as $key => $item){
                    if($item['id']==$ritem['id']){
                        $existdata[]=$item['id'];
                        $ritem['isnew']=0;
                        if(strtotime($item['update_time'])<strtotime($ritem['update_time'])){
                            $ritem['isupdate']=1;
                            $ritem['local_update_time']=strtotime($item['update_time']);
                        }

                        $ritem['update_time']=strtotime($ritem['update_time']);
                        $ritem['ismanage']=1;
                        $data[]=$ritem;
                        $flag = false;
                    }
                }
                if($flag){
                    $ritem['isnew']=1;
                    $ritem['update_time']=strtotime($ritem['update_time']);
                    $remotedata[]=$ritem;
                }
            }
            //获取原有的数据,可能是别的用户创建的系统
            foreach ($datas  as $key => $item){
                if(!in_array($item['id'],$existdata)){
                    $item['isnew']=0;
                    $item['ismanage']=1;
                    $item['update_time']=strtotime($item['update_time']);
                    $data[]=$item;
                }
            }
        }else{
            foreach ($datas  as $key => $item){
                $item['isnew']=0;
                $item['ismanage']=1;
                $item['update_time']=strtotime($item['update_time']);
                $data[]=$item;
            }
        }


        include $this->template();
    }


    public function auth(){
        global $_W;
        global $_GPC;
        if($_W['ispost']){
            global $_W;
            $url = rtrim($_W['siteroot'], '/');
            $auth =[];
            $auth['referrer']=$url;
            $auth['username']=safe_gpc_string($_GPC['username']);
            $auth['password']=safe_gpc_string($_GPC['password']);
            $query = base64_encode(json_encode($auth));
            $auth_url = 'http://www.diygw.com/auth/profile.html';
            $content = ihttp_post($auth_url,['query'=>$query]);
            if(isset($content['content'])&& !empty($content['content'])){
                $auths=json_decode($content['content'],true);
                if($auths['status']=='error'){
                    message($auths['message'], '', 'error');
                }else{
                    try {
                        // 开启一个事务，关闭自动提交
                        pdo()->begin();
                        // 添加或更新项目数据
                        $value=$auths['content'];
                        $value['username']=$auth['username'];
                        $value['referrer'] =$auth['referrer'];
                        $data['value'] = json_encode($value);
                        $data['name'] ='auth';
                        $data['uniacid'] =$_W['uniacid'];
                        if ($config = pdo_get(getTableName('CONFIG'), array('name' => 'auth'))) {
                            $data['update_time'] = date("Y-m-d H:i:s",TIMESTAMP);
                            $res = pdo_update(getTableName('CONFIG'),$data , array('id' => $config['id']));
                        } else {
                            $data['create_time'] = date("Y-m-d H:i:s",TIMESTAMP);
                            $data['update_time'] = $data['create_time'];
                            $res = pdo_insert(getTableName('CONFIG'), $data);
                        }
                        if(!$res) {
                            throw new Exception("授权失败！");
                        }
                        // 操作成功则提交更改
                        pdo()->commit();
                        message('授权成功','', 'success');
                    } catch (Exception $e){
                        // 失败回滚
                        pdo()->rollback();
                        var_dump($e);
                        message('授权失败', '', 'error');
                        die;
                    }
                }
            }else{
                message('授权失败', '', 'error');
            }
        }
        $data = pdo_get(getTableName('CONFIG'), array('name' => 'auth'), array('name', 'value'));
        if($data){
            $auth=json_decode($data['value'],true);
        }
        include $this->template();
    }

    function download($package) {
        $package = $this->sign($package);
        $headers = array('content-type' => 'application/x-www-form-urlencoded');
        $dat = ihttp_request('http://www.diygw.com/auth/file.html', $package, $headers, 300);
        if(is_error($dat)) {
            return error(-1, '网络存在错误， 请稍后重试。' . $dat['message']);
        }
        if($dat['content'] == 'success') {
            return true;
        }
        $ret = @json_decode($dat['content'], true);
        if(is_error($ret)) {
            return $ret;
        } else {
            $post = @json_decode($ret['content'], true);
            $data = base64_decode($post);
            if (base64_encode($data) !== $post) {
                $data = $post;
            }
            $ret = iunserializer($data);
            $gz = function_exists('gzcompress') && function_exists('gzuncompress');
            $file = base64_decode($ret['file']);
            if($gz) {
                $file = gzuncompress($file);
            }
            $path = IA_ROOT . $ret['path'];
            load()->func('file');
            @mkdirs(dirname($path));
            if (file_put_contents($path, $file)) {
                return true;
            } else {
                return error(-1, '写入失败');
            }
        }
    }

    /**
     * 生成目录
     * @param  string  $path 目录
     * @param  integer $mode 权限
     * @return boolean
     */
    public function createDir($path, $mode = 0755) {
        if(is_dir($path)) return TRUE;
        $path = str_replace("\\", "/", $path);
        if(substr($path, -1) != '/') $path = $path.'/';
        $temp = explode('/', $path);
        $cur_dir = '';
        $max = count($temp) - 1;
        for($i=0; $i<$max; $i++) {
            $cur_dir .= $temp[$i].'/';
            if (@is_dir($cur_dir)) continue;
            @mkdir($cur_dir, $mode, true);
            @chmod($cur_dir, $mode);
        }
        return is_dir($path);
    }

    public function setup(){
        global $_W;
        global $_GPC;
        $package = [];
        $package['type'] = 'dashboard';
        $package['id'] = safe_gpc_string($_GPC['pid']);
        $package = $this->sign($package);
        $headers = array('content-type' => 'application/x-www-form-urlencoded');
        $dat = ihttp_request('http://www.diygw.com/auth/file.html', $package, $headers, 300);
        if(is_error($dat)) {
            return message('请求服务器错误！' . $dat['message'],'','error');
        }
        $this->createDir(IA_ROOT.'/data/update');
        $destination = IA_ROOT.'/data/update/'.date('Ymd', TIMESTAMP).'.zip';
        if(!dat['content']){
            return message('请求服务器错误！' . $dat['message'],'','error');
        }

        switch ($dat['headers']['Content-Type']) {
            case 'application/octet-stream;charset=ISO-8859-1':
                @file_put_contents($destination,$dat['content']);
                /*$file = fopen($destination,"w+");
                fputs($file,$dat['content']);//写入文件
                fclose($file);*/
                break;
            default:
                $ret = @json_decode($dat['content'], true);
                break;
        }
        if(array_key_exists('status', $ret)) {
            return message($ret['message'],'','error');
        } else {
            try{
                $archive = new PclZip();
                $archive->PclZip($destination);
                $this->createDir(IA_ROOT.'/addons/diygwcom_app/template/attachment');
                $this->createDir(IA_ROOT.'/addons/diygwcom_app/template/data');
                if(!$archive->extract(PCLZIP_OPT_PATH, IA_ROOT.'/addons/diygwcom_app/', PCLZIP_OPT_REPLACE_NEWER)) {
                    return message('升级失败，请开启template文件夹权限','','error');
                }
                unlink($destination);
                $file = realpath(IA_ROOT.'/addons/diygwcom_app/template/data/'.$package['id'].'/'.date('Ymd', TIMESTAMP).'.txt');

                if (is_file($file)) {
                    $content = file_get_contents($file);
                    $content = @json_decode($content, true);
                    if($content){
                        // 开启一个事务，关闭自动提交
                        pdo()->begin();
                        $dashboard= $content['dashboard'];//获取应用
                        $dashboardscene= $content['dashboardscene'];//获取场景
                        $dashboardextend= $content['dashboardextend'];//获取扩展
                        $dashboardpage= $content['dashboardpage'];//获取页面
                        $dashboardtable= $content['dashboardtable'];//获取表格
                        $dashboardmodel= $content['dashboardmodel'];
                        $dashboardattribute= $content['dashboardattribute'];
                        $modeldata= $content['modeldata'];
                        load()->func('db');
                        foreach ($dashboardtable as $key => $remote )
                        {
                            $remote['tablename']="ims_diygwcom_app_".$remote['tablename'];
                            $name = substr($remote['tablename'], 4);
                            $local = db_table_schema(pdo(), $name);
                            $sqls = db_table_fix_sql($local, $remote);
                            $error = false;
                            foreach ($sqls as $sql) {
                                if (pdo_query($sql) === false) {
                                    $error = true;
                                    continue;
                                }
                            }
                        }
                        //插入模型数据

                        pdo_delete(getTableName('DASHBOARD'), array('id' => $dashboard['id']));
                        $dashboard['uniacid']=$_W['uniacid'];
                        pdo_insert(getTableName('DASHBOARD'),$dashboard);

                        foreach ($dashboardscene as $key => $item )
                        {
                            if($key==0){
                                $result = pdo_delete(getTableName('DASHBOARD_SCENE'), array('dashboard_id' => $item['dashboard_id']));
                            }
                            pdo_insert(getTableName('DASHBOARD_SCENE'),$item);
                        }

                        foreach ($dashboardextend as $key => $item )
                        {
                            if($key==0){
                                $result = pdo_delete(getTableName('DASHBOARD_EXTEND'), array('dashboard_id' => $item['dashboard_id']));
                            }
                            pdo_insert(getTableName('DASHBOARD_EXTEND'),$item);
                        }

                        foreach ($dashboardmodel as $key => $item )
                        {
                            $result = pdo_delete(getTableName('MODEL'), array('id' => $item['id']));
                            pdo_insert(getTableName('MODEL'),$item);
                        }

                        foreach ($dashboardattribute as $key => $item )
                        {
                            $result = pdo_delete(getTableName('ATTRIBUTE'), array('id' => $item['id']));
                            pdo_insert(getTableName('ATTRIBUTE'),$item);
                        }

                        $pagewebname=[];
                        $pagemobilename=[];
                        $pagewebname['/static/images'] = MODULE_ASSETS.'images';
                        $pagewebname['/data/data.html'] = $this->createWebUrl('data_data', array('m'=>'diygwcom_app'));
                        $pagewebname['/data/save.html'] = $this->createWebUrl('data_save', array('m'=>'diygwcom_app'));
                        $pagewebname['/data/remove.html'] =$this->createWebUrl('data_remove', array('m'=>'diygwcom_app'));

                        $pagemobilename['/static/images'] = MODULE_ASSETS.'images';
                        $pagemobilename['/static/img'] = MODULE_ASSETS.'images';
                        $pagemobilename['/data/data.html'] = DiygwcomUtil::to_mobile_url($this->createMobileUrl('data_data', array('m'=>'diygwcom_app')));
                        $pagemobilename['/data/save.html'] = DiygwcomUtil::to_mobile_url($this->createMobileUrl('data_save', array('m'=>'diygwcom_app')));
                        $pagemobilename['/data/remove.html'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('data_remove', array('m'=>'diygwcom_app')));
                        $pagemobilename['/xcx/cart/save.html'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('cart_save', array('m'=>'diygwcom_app')));
                        $pagemobilename['cart'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('cart_index', array('m'=>'diygwcom_app','dashboardid' => $dashboard['id'])));
                        $pagemobilename['order'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('order_index', array('m'=>'diygwcom_app','dashboardid' => $dashboard['id'])));
                        $pagemobilename['address'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('address_index', array('m'=>'diygwcom_app','dashboardid' => $dashboard['id'])));
                        $pagemobilename['empty'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('page_emptypage', array('m'=>'diygwcom_app','dashboardid' => $dashboard['id'])));

                        $pagemobilename['/xcx/cart/index.html?'] =DiygwcomUtil::to_mobile_url($this->createMobileUrl('cart_index', array('m'=>'diygwcom_app')))."&";

                        foreach ($dashboardpage as $key => $item )
                        {
                            if($item['template']=='mobile'){
                                $pagemobilename[$item["name"]]=DiygwcomUtil::to_mobile_url($this->createMobileUrl('page_index', array('m'=>'diygwcom_app','pid'=>$item["id"])));
                            }else{
                                $pagewebname[$item["name"]]=$this->createWebUrl('page_index', array('m'=>'diygwcom_app','pid'=>$item["id"]));
                            }
                        }

                        foreach ($dashboardpage as $key => $item )
                        {
                            if($key==0){
                                $result = pdo_delete(getTableName('PAGE'), array('dashboard_id' => $item['dashboard_id']));
                            }
                            if($item['template']=='mobile'){
                                $pagename=$pagemobilename;
                            }else{
                                $pagename=$pagewebname;
                            }
                            foreach ($pagename as $page => $value )
                            {
                                $item['content'] = str_replace("\"".$page."\"","\"".$value."\"",$item['content']);
                                $item['content'] = str_replace("url=\"".$page,"url=\"".$value,$item['content']);
                                $item['content'] = str_replace("src=\"".$page,"src=\"".$value,$item['content']);
                                $item['content'] = str_replace("img=\"".$page,"img=\"".$value,$item['content']);
                            }
                            pdo_insert(getTableName('PAGE'),$item);
                        }

                        foreach ($modeldata as $tablekey => $items )
                        {
                            foreach ($items as $item){
                                if (pdo_insert(getTableName($tablekey),$item) === false) {
                                    $error = true;
                                    continue;
                                }
                            }
                        }

                        // 操作成功则提交更改
                        pdo()->commit();
                        unlink($file);
                        return message('安装成功！' . $dat['message'],'','success');
                    }else{
                        message('安装错误文件为空', '', 'error');
                    }
                }

            }catch (Exception $e) {
                pdo()->rollback();
                var_dump($e);
                message('安装错误', '', 'error');
                die;
            }
        }
    }

    public function delete(){
        global $_W;
        global $_GPC;
        $item['dashboard_id'] = safe_gpc_string($_GPC['pid']);
        pdo_delete(getTableName('DASHBOARD'), array('id' => $item['dashboard_id']));
        pdo_delete(getTableName('DASHBOARD_SCENE'), array('dashboard_id' => $item['dashboard_id']));
        pdo_delete(getTableName('DASHBOARD_EXTEND'), array('dashboard_id' => $item['dashboard_id']));
        pdo_delete(getTableName('PAGE'), array('dashboard_id' => $item['dashboard_id']));
        pdo_delete(getTableName('ADDRESS'), array('dashboard_id' => $item['dashboard_id']));
        return message('删除成功',$this->createWebUrl('dashboard_index', array('m'=>'diygwcom_app')),'success');

    }
}